import frappe
import requests
import json
from datetime import datetime


def sync_item(doc, method=None):
    """
    将物料数据同步到MES系统
    
    参数:
        doc: 物料文档对象
        method: 触发方法名(after_insert/on_update/on_trash)
    """
    # 记录调试日志，确认函数被调用
    frappe.log_error(
        message=f"物料同步函数被调用: 文档={doc.name}, 方法={method}",
        title="Item Sync Debug"
    )

    # 检查是否需要同步（如果有custom_synchronize_to_mes字段）
    if hasattr(doc, "custom_synchronize_to_mes") and doc.custom_synchronize_to_mes != "是":
        frappe.log_error(
            message=f"物料未标记为同步到MES，跳过: {doc.name}",
            title="Item Sync Skipped"
        )
        return

    # 根据method确定操作类型
    if method == "after_insert":
        operation = "insert"
    elif method == "on_update":
        operation = "update"
    elif method == "on_trash":
        operation = "delete"
    else:
        operation = "update"  # 默认操作

    try:
        # 准备物料数据 - 只提取必要字段而不是整个文档
        # 这里列出物料的核心字段，根据实际需要调整
        item_data = {
            "itemCode": doc.item_code,
            "itemName": doc.item_name,
            "unitName": doc.stock_uom,
            "enableFlag": not doc.disabled,
            # 添加其他必要字段
        }

        # 准备完整的请求负载 - 格式与成功测试示例一致
        payload = {
            "recordId": doc.name,  # 使用文档名称作为记录ID
            "operation": operation,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "item": item_data
        }

        # API地址 - 使用测试成功的端点格式
        api_url = "http://117.161.137.2:24013/prod-api/mes/md/mditem/erpInto"

        # 记录请求信息
        frappe.log_error(
            message=f"发送物料同步请求: URL={api_url}, 物料={doc.name}, 负载={json.dumps(payload, default=str)[:500]}",
            title="Item Sync Request"
        )

        # 发送请求 - 与测试成功的方式完全一致
        response = requests.post(url=api_url, json=payload)

        # 记录同步结果
        frappe.log_error(
            message=f"物料同步结果: {doc.name}, 操作: {operation}, 状态码: {response.status_code}, 响应: {response.text[:200]}",
            title="Item Sync Result"
        )

        # 分析响应
        if response.status_code == 200:
            try:
                resp_data = response.json()
                if "code" in resp_data and resp_data["code"] == 200:
                    frappe.log_error(
                        message=f"物料同步成功: {doc.name}, 操作: {operation}",
                        title="Item Sync Success"
                    )
                else:
                    frappe.log_error(
                        message=f"API返回错误: {doc.name}, 代码: {resp_data.get('code')}, 消息: {resp_data.get('msg', '')}",
                        title="Item Sync API Error"
                    )
            except ValueError:
                frappe.log_error(
                    message=f"无法解析API响应: {doc.name}, 响应: {response.text[:200]}",
                    title="Item Sync Response Error"
                )

    except Exception as e:
        # 详细记录错误
        import traceback
        error_trace = traceback.format_exc()

        frappe.log_error(
            message=f"物料同步错误: {doc.name}, 操作: {operation}, 错误: {str(e)}\n\n堆栈跟踪:\n{error_trace}",
            title="Item Sync Error"
        )


def sync_work_order(doc, method=None):
    """
    将生产工单数据同步到MES系统

    参数:
        doc: 生产工单文档对象
        method: 触发方法名(after_insert/on_update/on_trash)
    """

    # 检查是否需要同步（如果有custom_synchronize_to_mes字段）
    if hasattr(doc, "custom_synchronize_to_mes") and doc.custom_synchronize_to_mes != "是":
        return

    # 根据method确定操作类型
    if method == "after_insert":
        operation = "insert"
    elif method == "on_update":
        operation = "update"
    elif method == "on_trash":
        operation = "delete"
    else:
        operation = "update"  # 默认操作

    try:
        # 准备物料数据 - 只提取必要字段而不是整个文档
        # 这里列出物料的核心字段，根据实际需要调整
        item_data = {
            "workorderCode": doc.name,
            "workorderName": doc.name,
            "productCode": doc.production_item,
            "productName": doc.item_name,
            "unitOfMeasure": doc.stock_uom,
            # "batchCode": doc.批次号,
            "quantity": doc.qty,
            "quantityProduced": doc.produced_qty,
            "orderNum": doc.sales_order,
            "requestDate": doc.expected_delivery_date,
            "status": doc.status,
        }

        # 准备完整的请求负载 - 格式与成功测试示例一致
        payload = {
            "recordId": doc.name,  # 使用文档名称作为记录ID
            "operation": operation,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "item": item_data
        }

        # API地址 - 使用测试成功的端点格式
        api_url = "http://117.161.137.2:24013/prod-api/mes/pro/workorder/erpInto"

        # 记录请求信息
        frappe.log_error(
            message=f"发送生产工单同步请求: URL={api_url}, 生产工单={doc.name}, 负载={json.dumps(payload, default=str)[:500]}",
            title="Work Order Sync Request"
        )

        # 发送请求 - 与测试成功的方式完全一致
        response = requests.post(url=api_url, json=payload)

        # 记录同步结果
        frappe.log_error(
            message=f"生产工单同步结果: {doc.name}, 操作: {operation}, 状态码: {response.status_code}, 响应: {response.text[:200]}",
            title="Work Order Sync Result"
        )

        # 分析响应
        if response.status_code == 200:
            try:
                resp_data = response.json()
                if "code" in resp_data and resp_data["code"] == 200:
                    frappe.log_error(
                        message=f"生产工单同步成功: {doc.name}, 操作: {operation}",
                        title="Work Order Sync Success"
                    )
                else:
                    frappe.log_error(
                        message=f"API返回错误: {doc.name}, 代码: {resp_data.get('code')}, 消息: {resp_data.get('msg', '')}",
                        title="Work Order Sync API Error"
                    )
            except ValueError:
                frappe.log_error(
                    message=f"无法解析API响应: {doc.name}, 响应: {response.text[:200]}",
                    title="Work Order Sync Response Error"
                )

    except Exception as e:
        # 详细记录错误
        import traceback
        error_trace = traceback.format_exc()

        frappe.log_error(
            message=f"生产工单同步错误: {doc.name}, 操作: {operation}, 错误: {str(e)}\n\n堆栈跟踪:\n{error_trace}",
            title="Work Order Sync Error"
        )
